package com.ruiyangwang.ListenBook.servlet.track;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruiyangwang.ListenBook.service.TrackService;
import com.ruiyangwang.ListenBook.util.Log;
import com.ruiyangwang.ListenBook.viewObject.StudioTrackListView;
import com.ruiyangwang.ListenBook.viewObject.UserV0;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author syzygy
 * @date 2022/07/12 16:36
 **/
@WebServlet("/studio/track/list.json")
public class ListJsonServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final TrackService trackService = new TrackService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Log.println("访问track/list.json");
        Log.println("QueryString" + req.getQueryString());
        //需要考虑边界情况
        //不做错误提示
        //page :页数
        int page;
        String pageString = req.getParameter("page");
        if (pageString == null || pageString.trim().isEmpty()){
            Log.println("请求体中没有任何参数,默认第一页");
            page = 1;
        } else {
            pageString =pageString.trim();
            try{
                page = Integer.parseInt(pageString);
            } catch (NumberFormatException c){
                Log.println("请求页码不是数字，默认第一页");
                page = 1;
            }
        }
        Log.println("page = " + page);

        //获取当前用户
        HttpSession session =req.getSession(false);
        UserV0 current = null;
        if(session != null){
                current = (UserV0) session.getAttribute("currentUser");
        }

        //用户未登录
        StudioTrackListView resView;
        if(current == null){
            Log.println("用户未登录");
            resView = new StudioTrackListView();
        }else{
            resView =trackService.listOfUser(current,page);
        }
        Log.println("准备序列化的对象" + resView);
        String json = objectMapper.writer().writeValueAsString(resView);
        Log.println("JSON 序列化的结果" + json);

        // json写入响应体
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter printWriter = resp.getWriter();
        Log.println("写入响应体中");
        printWriter.println(json);




    }
}